﻿using OdooRpcClient.Model.Base;
using OdooRpcClient.Model.Hr;
using PortaCapena.OdooJsonRpcClient;
using PortaCapena.OdooJsonRpcClient.Consts;
using PortaCapena.OdooJsonRpcClient.Converters;
using PortaCapena.OdooJsonRpcClient.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OdooRpcClient.Converters
{
    public static class ModelMapper
    {
        private const string OdooModelSuffix = "OdooModel";
        private const string OdooEnumSuffix = "OdooEnum";

        /// <summary>
        /// 通过odoo模型名称获取对应的实体类名称
        /// </summary>
        /// <param name="modelName"></param>
        /// <returns>
        /// className 类名称
        /// fullName 命名空间.类型名
        /// assemblyName 程序集
        /// </returns>
        public static string[] GetModelName(string modelName)
        {
            string className = string.Empty;
            string fullName = string.Empty;
            string assemblyName = string.Empty;
            bool isExist = false;
            List<string> strList = new List<string>();
            switch (modelName)
            {
                #region Hr
                case "hr.employee":
                    className = "HrEmployeeOdooModel";
                    fullName = "OdooRpcClient.Model.Hr.HrEmployeeOdooModel";
                    isExist = true;
                    break;
                case "hr.department":
                    className = "HrDepartmentOdooModel";
                    fullName = "OdooRpcClient.Model.Hr.HrDepartmentOdooModel";
                    isExist = true;
                    break;
                #endregion

                #region Sale
                case "sale.order":
                    className = "SaleOrderOdooModel";
                    fullName = "OdooRpcClient.Model.Sale.SaleOrderOdooModel";
                    isExist = true;
                    break;
                #endregion

                #region Base
                case "res.users":
                    className = "UsersOdooModel";
                    fullName = "OdooRpcClient.Model.Base.UsersOdooModel";
                    isExist = true;
                    break;
                case "ir.actions.report":
                    className = "ReportOdooModel";
                    fullName = "OdooRpcClient.Model.Base.ReportOdooModel";
                    isExist = true;
                    break;

                #endregion
            }
            assemblyName = "OdooRpcClient";
            string[] array = new string[3];
            if (isExist)
            {
                strList.Add(className);
                strList.Add(fullName);
                strList.Add(assemblyName);
                array = strList.ToArray();
            }
            return array;
        }

        //public static OdooRepository GetOdooRepository(string modelName, OdooConfig config)
        //{
        //    dynamic repository;
        //    switch (modelName)
        //    {                
        //        case "hr.employee":
        //            repository = new OdooRepository<EmployeeOdooModel>(config);
        //            break;
        //        case "hr.department":
        //            repository = new OdooRepository<DepartmentOdooModel>(config);
        //            break;


        //        case "res.users":
        //            repository = new UsersOdooModel();
        //            break;
        //        case "ir.actions.report":
        //            repository = new ReportOdooModel();
        //            break;
        //        case "res.lang":
        //            repository = new LangOdooModel();
        //            break;
        //        case "ir.model":
        //            repository = new IrModelOdooModel();
        //            break;
        //        case "ir.model.fields":
        //            repository = new IrModelFieldsOdooModel();
        //            break;
        //        default:
        //            return null;
        //    }
        //    return repository;
        //}

        public static string GenerateModelCode(string tableName, Dictionary<string, OdooPropertyInfo> properties)
        {
            var builder = new StringBuilder();
            builder.AppendLine($"[OdooTableName(\"{tableName}\")]");
            builder.AppendLine($"[JsonConverter(typeof({nameof(OdooModelConverter)}))]");
            builder.AppendLine($"public class {OdooModelMapper.ConvertOdooNameToDotNet(tableName)}{OdooModelSuffix} : IOdooModel");
            builder.AppendLine("{");

            foreach (var property in properties)
            {
                builder.AppendLine(string.Empty);
                builder.AppendLine($"   /// <summary>");
                builder.AppendLine($"   /// {OdooModelMapper.ConvertOdooNameToDotNet(property.Key)}");
                builder.AppendLine($"   /// {OdooModelMapper.ConvertOdooNameToDotNet(property.Value.Type)}");
                if (!string.IsNullOrEmpty(property.Value.Help))
                    builder.AppendLine($"   /// {property.Value.Help}");
                if (property.Value.ResultRequired)
                    builder.AppendLine("   /// required");
                if (!string.IsNullOrEmpty(property.Value.Relation))
                    builder.AppendLine($"   /// {property.Value.Relation}");
                if (!string.IsNullOrEmpty(property.Value.RelationField))
                    builder.AppendLine($"   /// {property.Value.RelationField}");
                
                builder.AppendLine($"   /// <summary>");
                builder.AppendLine($"   [JsonProperty(\"{property.Key}\")]");
                builder.AppendLine($"   [Description(\"{OdooModelMapper.ConvertOdooNameToDotNet(property.Key)}\")]");
                builder.AppendLine($"   public {OdooModelMapper.ConvertToDotNetPropertyTypeName(property, tableName)} {OdooModelMapper.ConvertOdooNameToDotNet(property.Key)} {{ get; set; }}");
            }
            builder.AppendLine("}");

            var selectionsProps = properties.Where(x => x.Value.PropertyValueType == OdooValueTypeEnum.Selection).ToList();

            foreach (var property in selectionsProps)
            {
                builder.AppendLine(string.Empty);
                builder.AppendLine(string.Empty);

                if (!string.IsNullOrEmpty(property.Value.Help))
                    builder.AppendLine("// " + property.Value.Help.Replace("\n", "\n // "));

                builder.AppendLine($"[JsonConverter(typeof(StringEnumConverter))]");
                builder.AppendLine($"public enum {OdooModelMapper.ConvertOdooNameToDotNet(property.Value.String)}{OdooModelMapper.ConvertOdooNameToDotNet(tableName)}{OdooEnumSuffix}");
                builder.AppendLine("{");

                for (int i = 0; i < property.Value.Selection.Length; i++)
                {
                    string[] item = property.Value.Selection[i];

                    if (i != 0)
                        builder.AppendLine(string.Empty);
                    builder.AppendLine($"   [EnumMember(Value = \"{item[0]}\")]");
                    builder.AppendLine($"   {OdooModelMapper.ConvertOdooNameToDotNet(item[1])} = {i + 1},");
                }
                builder.AppendLine("}");
            }

            return builder.ToString();
        }

        //public GetFieldNameByCurrentLanguage(string tableName, string langName, OdooConfig config)
        //{
        //    var IrModeRepository = new OdooRepository<IrModelOdooModel>(config);
        //    IrModeRepository.Config.Context.Language = langName;

        //    var modelResult =  IrModeRepository.Query()
        //        .Where(x => x.Model, OdooOperator.EqualsTo, tableName)
        //        //.Select(x => new
        //        //{
        //        //    x.Id,
        //        //    x.Model,
        //        //    x.FieldId,
        //        //})
        //        .FirstOrDefaultAsync();

        //    var IrModelFieldsRepository = new OdooRepository<IrModelFieldsOdooModel>(config);
        //    IrModelFieldsRepository.Config.Context.Language = langName;
        //    if (modelResult.Succeed)
        //    {
        //        var fieldResult =  IrModelFieldsRepository.Query()
        //        .Where(x => x.Model, OdooOperator.EqualsTo, modelResult.Value.Model)
        //        .Select(x => new
        //        {
        //            x.Name, //字段名称
        //                        x.FieldDescription, //字段标签
        //                        x.Ttype, //字段类型
        //                        x.Help, //字段帮助
        //                        x.Required, //必须的
        //                        x.Relation, //关联的模型
        //                        x.RelationField, //关联字段
        //                        x.Related, // 高级属性关联字段
        //                    })
        //        .ToListAsync();
        //        if (fieldResult.Succeed)
        //        {
        //            string info = "";
        //            foreach (var item in fieldResult.Value)
        //            {
        //                info += item.Name + "|"
        //                    + item.FieldDescription + "|"
        //                    + item.Ttype + "|"
        //                    + item.Help + "|"
        //                    + "\n";
        //            }

        //        }

        //    }
        //}
    }
}
